package game.domain;

import game.configuration.Configuration;
import game.movement.Moveable;
import game.movement.MovementManager;
import game.shapes.BoundingBox;

import javax.vecmath.Point2d;
import java.awt.*;

public class Asteroid implements Moveable, game.domain.Controlable, Boundable {
	private final Color colour;
	private boolean disabled;
	private double heading;
	private final MovementManager movementManager;
	private final int numberOfSides;
	private final PolygonGenerator polygonGenerator = new PolygonGenerator();
	private final Point2d position;
	private final int size;
	private double speed;

	public Asteroid(Point2d position, double heading, int numberOfSides, int size, Color colour, int maxWidth, int maxHeight) {
		this.position = position;
		this.numberOfSides = numberOfSides;
		this.size = size;
		movementManager = new MovementManager(this, maxWidth, maxHeight, false);
		this.heading = heading;
		speed = 1.0;
		this.colour = colour;
	}

	public void accellerate() {
		movementManager.accelerate();
	}

	public void animate() {
		movementManager.moveAndScreenWrap();
	}

	public void decellerate() {
		movementManager.decelerate();
	}

	public void draw(Graphics2D graphics) {
		if (!disabled) {
			if (Configuration.getInstance().isDebugEnabled()) {
				graphics.setColor(Color.blue);
				graphics.draw(getBoundingBox().getRectangle());

				graphics.setColor(Color.DARK_GRAY);
				graphics.drawString(":-)", (int) position.x, (int) position.y);
			}

			// TODO Optimise this so it only regenerates when position changes
			Polygon polygon = generatePolygon();

			graphics.setColor(colour);
			graphics.drawPolygon(polygon);

		}
	}

	private Polygon generatePolygon() {
		return polygonGenerator.generate(position, heading, numberOfSides, size);
	}

	public BoundingBox getBoundingBox() {
		if (!disabled) {
			return new BoundingBox(generatePolygon().getBounds());
		}
		return null;
	}

	public double getDirection() {
		// TODO Auto-generated method stub
		return 0;
	}

	public double getHeading() {
		return heading;
	}

	public Point2d getPosition() {
		return position;
	}

	public double getSpeed() {
		return speed;
	}

	public boolean intersects(Boundable boundable) {
		if (boundable == this) {
			// cant intersect with yourself
			return false;
		}
		return generatePolygon().intersects(boundable.getBoundingBox().getRectangle());
	}

	public boolean intersects(Point2d point) {
		return generatePolygon().contains(point.x, point.y);
	}

	public boolean isDisabled() {
		return disabled;
	}

	public void setDirection(double direction) {
		// TODO Auto-generated method stub

	}

	public void setDisabled() {
		disabled = true;
	}

	public void setHeading(double heading) {
		this.heading = heading;
	}

	public void setSpeed(double speed) {
		this.speed = speed;
	}

	public void turnLeft() {
		movementManager.turnLeft();
	}

	public void turnRight() {
		movementManager.turnRight();
	}
}
